#!/usr/bin/env python
#
# Copyright 2010 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""XMPPHandler receives and responds to XMPP messages.

XMPPHandler is a webapp.RequestHandler that receives XMPP messages from 
arbitrary user accounts, and responds to them with random words sourced
from Google Buzz.
"""


__author__ = 'Vic Fryzel <vicfryzel@google.com>'


import random
from google.appengine.ext import db
from google.appengine.api import xmpp
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from gfemmebot.word_list import WordList 


class XMPPHandler(webapp.RequestHandler):
  """Handles incoming XMPP requests to gfemmebot.
  
  Upon receiving an incoming XMPP message, do the following:
    - Fetch a random word from the word list in the data store
    - Respond to the incoming message with that word
  """

  def post(self):
    """Receive an incoming XMPP message and respond with a random word.
    
    Requires that a message is contained within self.request.POST.
    """
    message = xmpp.Message(self.request.POST)
    word_lists = db.GqlQuery("SELECT * FROM WordList")
    for word_list in word_lists:
      words = word_list.words.split()
      word_num = random.randint(0, len(words))
      message.reply(words[word_num])
      return
    message.reply("I don't know any words!")


# The application container to run an XMPPHandler and map it to the preset
# XMPP chat URI.
application = webapp.WSGIApplication(
    [('/_ah/xmpp/message/chat/', XMPPHandler)],
    debug=True)

def main():
  """Run the XMPPHandler application."""
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
